package com.tacc.weixin.controller;


import com.tacc.tyun.common.jedis.RedisService;
import com.tacc.tyun.model.WxAccount;
import com.tacc.tyun.model.info.WxAccountInfo;
import com.tacc.tyun.service.WxAccountService;
import com.tacc.tyun.util.SpringContextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 使用redis进行缓存
 */
public class WxRedisCacheClient {

	private final static RedisService redisService = (RedisService) SpringContextUtils.getBean("redisService");
	private final static WxAccountService wxAccountService = (WxAccountService) SpringContextUtils.getBean("wxAccountService");
	//服务器内存的方式缓存wxAccountInfo
	private static Map<String,WxAccountInfo> wxAccountInfoMap = new HashMap<String,WxAccountInfo>();
	//redis缓存wxAccountInfo

	//isUpdate：是否更新到数据库
	public static void addWxAccountInfo(WxAccountInfo account,boolean isUpdate){
		if(account != null && !wxAccountInfoMap.containsKey(account.getId())){
			wxAccountInfoMap.put(account.getId(), account);
			if(isUpdate){
				WxAccount wxAccount= wxAccountService.acceptEntity();
				wxAccount.setAccessToken(account.getAccessToken());
				wxAccount.setExpiresIn(account.getExpiresIn());
				wxAccount.setAccessTokenEndTime(account.getAccessTokenEndTime());
				wxAccountService.updateByPrimaryKey(wxAccount);
			}
		}
	}

	public static WxAccountInfo getWxAccountInfo(String account){
		return wxAccountInfoMap.get(account);
	}

	//获取唯一的公众号,如果需要多账号，请自行处理
	public static WxAccountInfo getSingleWxAccountInfo(){
		WxAccountInfo sigleAccount = null;
		for(String key : wxAccountInfoMap.keySet()){
			sigleAccount = wxAccountInfoMap.get(key);
			break;
		}
		if(sigleAccount==null){
			sigleAccount=acceptWxAccountInfoForDatabases();
			addWxAccountInfo(sigleAccount,false);
		}
		return sigleAccount;
	}

	private static WxAccountInfo acceptWxAccountInfoForDatabases(){
		WxAccountInfo sigleAccount=new WxAccountInfo();
		WxAccount wxAccount= wxAccountService.acceptEntity();
		if(wxAccount !=null){
			sigleAccount.setId(wxAccount.getId());
			sigleAccount.setAppid(wxAccount.getAppid());
			sigleAccount.setAppsecret(wxAccount.getAppsecret());
			sigleAccount.setAccessToken(wxAccount.getAccessToken());
			sigleAccount.setUrl(wxAccount.getUrl());
			sigleAccount.setAccessTokenEndTime(wxAccount.getAccessTokenEndTime());
			sigleAccount.setToken(wxAccount.getToken());
			sigleAccount.setBaseURL(wxAccount.getBaseURL());
		}
		return sigleAccount;
	}


}


